var md5Encrypt = require('../../../../util/md5/md5.js');
let app = getApp()
Page({
  data: {
    appInfo:getApp(),
    orderDetail: {},
    ossImg: `${app.globalData.imgUrl}/applet_web_images/new_image`,
    imgUrl: "",
    statusImg: "", //状态对应图标
    statusName: "", //状态名字
    statusDes: "", //状态描述
    phone_secret: "", //隐秘后的手机号
    user_phone: "", //手机号
    order_id: "", //订单号
    express: "",//快递公司名称
    exp_number: "",//快递单号
    depositState: "", //-1不免，0半免，1全免
    shadowAnimation: [], //动画-背景
    layerAnimation: [], //动画-弹出层
    freePaymentHidden: true, //免密支付弹出层
    authorizedHidden: true, //支付宝资金授权弹出层
    cancelOrderHidden: true, //取消订单弹出层
    frozenHidden: true,//冻结押金弹出层
    clickindex: -1,
    choosedReason: "", //选择的取消原因
    cancelReason: [
      {
        cho: 0,
        value: '想要重新下单',
        img: '/image/confirm-order-circle.png',
      }, {
        cho: 0,
        value: '商品价格较贵',
        img: '/image/confirm-order-circle.png',
      }, {
        cho: 0,
        value: '等待时间较长',
        img: '/image/confirm-order-circle.png',
      }, {
        cho: 0,
        value: '是想了解流程',
        img: '/image/confirm-order-circle.png',
      }, {
        cho: 0,
        value: '不想要了',
        img: '/image/confirm-order-circle.png',
      }
    ],
    form_id: "",
    ismoveMenuBtn: false,
    isloadorderDetail: false,//是否调用
    kefuisShow: false,//客服弹框
    newuid:0,
    visible: false,
    retentionCancelOrder: false, // 是否取消订单挽留弹窗
    orderStr: '', // 支付宝继续下单必备参数
    isHideToExamineProup: false, // 是否显示催审核弹窗
    isHideDeliveryProup: false, // 是否显示催发货弹窗
    isShowFirstMonthProup: false, // 首月1元挽留弹窗
    currentDate: '', // 首月1元当前有效期
    isHideOriginFirstInstallmentRent: true, // 是否隐藏原首期实付金额
    isHideRemainingTotalRent: true, // 是否隐藏剩余总租金
    isHidePlaceOrderPopup: false, // 继续下单挽留弹窗
    isHideEarnestMoney: false, // 是否隐藏保证金
    buyoutPriceVisible: false, // 买断价弹窗
    buyoutList: [] // 买断价列表
  },
  handleVisibleChange(visible, e) {
    this.setData({ visible });
  },
  jumpHomePage() {
    this.setData({ visible: false });
    my.switchTab({
      url: '../../../rent/rent' 
    })
  },

  // 跳转保证金
  jumpEarnestMoney() {
    const {
      order_ensure_amount,
      order_goods_insurance,
      goods_lease_way_id,
      order_ensure_amount_status,
      order_goods_rent_info: {
        buy_money
      }
     } = this.data.orderDetail
    const money = `?order_ensure_amount=${order_ensure_amount}&order_goods_insurance=${order_goods_insurance}&buy_money=${buy_money}`
    const state = `&goods_lease_way_id=${goods_lease_way_id}&order_ensure_amount_status=${order_ensure_amount_status}`
    my.navigateTo({
      url: `/page/mine/myorders/performanceBond/performanceBond${money}${state}`
    })
  },

  jumpPage({ target: { dataset: {url, order_id, attr_id, goods_id, relet_order_no}}}) {
    if(order_id || attr_id || goods_id || relet_order_no) {
      my.navigateTo({
        url: 
        `${url}?order_id=${order_id}&attr_id=${attr_id}&goods_id=${goods_id}&relet_order_no=${relet_order_no}`
      })
    } else {
      my.navigateTo({
        url
      })
    }
  },

  // 复制文本
  copyOrderCode({ target: {dataset: {order_id: text}}}) {
    my.setClipboard({
      text, // 剪贴板数据
      success: (res) => {
        my.showToast({
          type: 'success',
          content: '复制成功！'
        });
      },
    });
  },

  //显示弹出层背景
  showShadow() {
    var animation = my.createAnimation({
      duration: 150,
      timingFunction: 'cubic-bezier(.55, 0, .55, .2)',
    });

    this.shadowAnim = animation;

    animation.opacity(1).step();
    this.setData({
      shadowAnimation: animation.export(),
    });
  },
  // 隐藏弹出层背景
  hideShadow() {
    this.shadowAnim.opacity(0).step();
    this.setData({
      shadowAnimation: this.shadowAnim.export(),
    });
  },
  // 显示弹出层
  showLayer() {
    var animation = my.createAnimation({
      duration: 150,
      timingFunction: 'cubic-bezier(.55, 0, .55, .2)',
    });
    this.layerAnim = animation;
    animation.opacity(1).scale(1).step();
    this.setData({
      layerAnimation: animation.export(),
    });
  },
  // 隐藏弹出层
  hideLayer() {
    this.layerAnim.scale(.8).opacity(0).step();
    this.setData({
      layerAnimation: this.layerAnim.export(),
    });
  },
  // 确定取消挽留弹窗
  handleCancell(e) {
    const { confirmCancel } = e.target.dataset
    this.setData({
      cancelOrderHidden: !this.data.cancelOrderHidden,
      [confirmCancel]: false
    });
  },  



  // 暂不取消
  not_cancel(e) {
    const { noCancel } = e.target.dataset
    this.setData({
      [noCancel]: false
    })
  },
  //打开弹出层
  showPanel(e) {
    if (e.currentTarget.dataset.origin == "freePayment") {
      this.setData({
        freePaymentHidden: !this.data.freePaymentHidden,
      });
    } else if (e.currentTarget.dataset.origin == "authorized") {
      this.setData({
        authorizedHidden: !this.data.authorizedHidden,

      });
    } else if (e.currentTarget.dataset.origin == "cancelOrder") { 
      // 取消订单
      const { total_voucher_amount } = this.data.orderDetail.order_goods_rent_info
      
      const { one_yuan } = this.data.orderDetail

      if(one_yuan) { // 如果是首月1元商品
        this.setData({
          isShowFirstMonthProup: true
        })
      } 

      if(total_voucher_amount) { // 如果使用到了优惠券
        this.setData({
          retentionCancelOrder: true
        });
      }

      if(!one_yuan && !total_voucher_amount) {
        this.setData({
          cancelOrderHidden: false
        })
      }


    } else if (e.currentTarget.dataset.origin == "frozen") {
      this.setData({
        frozenHidden: !this.data.frozenHidden,
        form_id: e.detail.formId
      });
    }


    this.showShadow();
    this.showLayer();
  },

  //关闭弹出层
  hidePanel(e) {
    this.hideShadow();
    this.hideLayer();

    this.setData({
      freePaymentHidden: true,
      authorizedHidden: true,
      cancelOrderHidden: true,
      frozenHidden: true,
    });
  },

  //获取订单详情
  getDetail(action) {
      var obj = this;
    
    var app = getApp();

    obj.setData({
      isloadorderDetail: true
    })
    var orderDetailParam = {
      version: app.globalData.version,
      device: app.globalData.device,
      signType: app.globalData.signType,
      order_id: obj.data.order_id,
    }
    var orderDetailStr = md5Encrypt.md5(orderDetailParam);

    //请求数据
    
    console.log(orderDetailParam)
    // console.log(orderDetailStr)
    my.request({
      url: app.globalData.testUrl + '/api/order/getOrderDetail',
      method: 'POST',
      data: {
        order_id: obj.data.order_id
      },
      dataType: 'json',
      success: function (res) {
        if (res.data.code !== 1) {
          
          // my.showToast({
          //   type: "none",
          //   content: res.data.msg,
          //   duration: 1000
          //   // success:()=>{
          //   //   my.navigateBack()
          //   // }
          // })
            }
        const { data } = res.data
        var user_phone = data.receiver_phone;
        var phone_secret = "";
        if (user_phone && user_phone != "") {
          phone_secret = user_phone.replace(user_phone.substr(3, 4), '****');
        }
        data.order_goods_rent_info.statusImg =  ((order_status) => {
          const data = {
            0: '/image/orderDetail/no_complete_order.png',
            1: '/image/orderDetail/audit.png',
            2: '/image/orderDetail/to_be_paid.png',
            3: '/image/orderDetail/take_over.png',
            4: '/image/orderDetail/under_lease.png',
            6: '/image/orderDetail/complete.png',
            7: '/image/orderDetail/overdue.png',
            8: '/image/orderDetail/no_complete.png',
            9: '/image/orderDetail/no_complete.png',
            13: '/image/orderDetail/under_lease.png'
          }
          return data[order_status]
        })(data.order_status)

        // 获取催发货催审核缓存
        const getReviewShipmentCache = (storageKey, isHideBtn) => {
          let { data: array } = my.getStorageSync({ key: storageKey });
          if(Array.isArray(array) && array.includes(data.order_id)) {
            data[isHideBtn] = true
          }
        }

        getReviewShipmentCache('isUrgeToExamineOrderList', 'isUrgeToExamine')
        getReviewShipmentCache('isDeliveryOrderList', 'isDelivery')

        let {
          order_month_rent,
          oder_first_month_rent,
          order_actual_month_rent
         } = data.order_goods_rent_info;

        const convertNumbers = () => {
          let order_monthly_rent = data.order_monthly_rent
          order_month_rent = order_month_rent && Number(order_month_rent)
          oder_first_month_rent = oder_first_month_rent && Number(oder_first_month_rent)
          order_actual_month_rent = order_actual_month_rent && Number(order_actual_month_rent)
          
          order_monthly_rent = order_monthly_rent && Number(order_monthly_rent)
          if(order_month_rent === oder_first_month_rent) { // 价格相同隐藏原首期租金
            obj.setData({
              isHideOriginFirstInstallmentRent: false
            })
          }

          if(order_monthly_rent === order_actual_month_rent) {
            obj.setData({
              isHideRemainingTotalRent: false
            })
          }
        }

        convertNumbers()
         
        if(Number(data.order_ensure_amount) > 0) {
          obj.setData({
            isHideEarnestMoney:true
          })
        } else {
          obj.setData({
            isHideEarnestMoney:false
          })
        }

        const { order_gradient_buyout_price_info } = data

        obj.setData({
          orderDetail: data,
          statusName: data.order_status_name,
          statusDes: data.order_ms,
          phone_secret: phone_secret,
          user_phone: user_phone,
          exp_number: data.exp_number,
          express: data.express,
          buyoutList: order_gradient_buyout_price_info
        });
  
        if (action == "load") {
          my.hideLoading(); //加载结束
        } else if (action == "pulldown") {
          my.stopPullDownRefresh();  //停止刷新
        }

      },
      complete: function (res) {
        if (action == "load") {
          my.hideLoading(); //加载结束
        } else if (action == "pulldown") {
          my.stopPullDownRefresh();  //停止刷新
        }
      }
    });
      
    

    
  },

  //复制快递单号
  copyNum(e) {
    my.setClipboard({
      text: e.currentTarget.dataset.delivery,
      success: function (e) {
        my.showToast({
          type: 'none',
          content: '复制成功',
          duration: 1200,
          success: () => {
          },
        });
      }
    });
  },

  // 催促审核或发货
  urgeMethod({ target: { dataset: {order_id, key, visible}}}) {
    let { data } = my.getStorageSync({ key });
    const result =  data || []
    result.push(order_id)
    my.setStorage({
      key,
      data: result,
      success: () => {
        this.getDetail('load')

        const { isHideDeliveryProup, isHideToExamineProup } = this.data
        isHideDeliveryProup && this.setData({
          isHideDeliveryProup: false
        })
        isHideToExamineProup && this.setData({
          isHideToExamineProup: false
        })
        this.setData({
          [visible]: true
        })

        setTimeout(() => {
          this.setData({
            [visible]: false
          })
        }, 10000)

      }
    })
  },


  // 选择取消原因
  choCancelReason(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      choosedReason: this.data.cancelReason[index].value,
      clickindex: index,
    })
  },

  openBuyoutPrice() {
    this.setData({
      buyoutPriceVisible: true
    })
  },

  closeBuyoutPrice() {
    this.setData({
      buyoutPriceVisible: false
    })
  },


  // “再考虑下”
  closeCancelReason() {
    this.hideShadow();
    this.hideLayer();

    this.setData({
      choosedReason: "",
      clickindex: -1,
      freePaymentHidden: true,
      authorizedHidden: true,
      cancelOrderHidden: true
    });
  },

  // 提交取消原因
  sureToCancel(e) {
    var obj = this;
    var app = getApp();

    if (this.data.choosedReason == '') {
      my.showToast({
        type: 'none',
        content: '请选择取消原因',
        duration: 1200,
        success: () => {
        },
      });
    } else {
      //加载动画
      my.showLoading({
        content: '加载中...',
        delay: 0,
      });

      let { testUrl, user_id: zm_user_id } = app.globalData
      my.request({
        url: `${testUrl}/api/order/userApplyCancelOrder`,
        method: 'POST',
        data: {
          order_id: obj.data.orderDetail.order_id,
          order_remarks: obj.data.choosedReason,
          zm_user_id
        },
        dataType: 'json',
        success:  (res) => {
          const { code } = res.data
          my.hideLoading(); //加载结束

          if (code === 1) {
            my.showToast({
              type: 'success',
              content: '取消成功',
              duration: 1200,
              success:  () => {
            
                my.redirectTo({
                  url: '/page/mine/myorders/myorders?showGroup=1'
                })
              }
            });
          } else {
            my.showToast({
              type: 'none',
              content: '操作失败',
              duration: 1200,
            });
          }
        },
        fail:  () => {
          my.showToast({
            type: 'none',
            content: '操作失败',
            duration: 1200,
          });
        },
        complete:  () => {
          my.hideLoading(); //加载结束

          obj.hideShadow();
          obj.hideLayer();

          obj.setData({
            freePaymentHidden: true,
            authorizedHidden: true,
            cancelOrderHidden: true
          });
        }
      })
    }
  },

  //确认收货
  confirmReceipt() {
    var obj = this;
    var app = getApp();
    //加载动画
    my.showLoading({
      content: '加载中...',
      delay: 0,
    });

    var receiptParam = {
      version: app.globalData.version,
      device: app.globalData.device,
      signType: app.globalData.signType,
      order_id: obj.data.orderDetail.order_id,
    }
    var receiptStr = md5Encrypt.md5(receiptParam);

    my.request({
      url: app.globalData.testUrl + '/Order/orderConfirm',
      method: 'POST',
      data: {
        version: app.globalData.version,
        device: app.globalData.device,
        signType: app.globalData.signType,
        order_id: obj.data.orderDetail.order_id,
        token: receiptStr,
      },
      dataType: 'json',
      success: function (res) {
        // console.log(res.data);

        if (res.data.status == '1001') {
          obj.setData({
            statusName: res.data.data.order_status_name,
            statusDes: res.data.data.order_status_ms,
            statusImg: '/image/orderdetail-using.png'
          })
          my.showToast({
            type: 'success',
            content: '收货成功',
            duration: 1200,
            success: function () {
              //刷新数据
              obj.getDetail("refresh");
            }
          });
        } else if (res.data.status == '1002') {
          my.showToast({
            type: 'none',
            content: res.data.data.order_status_ms,
            duration: 1200,
          });
        } else {
          my.showToast({
            type: 'none',
            content: '操作失败',
            duration: 1200,
          });
        }
      },
      complete: function (res) {
        my.hideLoading(); //加载结束
      }
    });
  },


  // 查看订单
  toMyOrders() {
    my.navigateTo({
      url: '../myorders?id=1&status=1'
    });
  },
  contract() {//下载查看合同
    let vm = this;
    var app = getApp();
    if (my.canIUse("openDocument")) {
      my.showLoading({
        content: '加载中...'
      });
      my.request({
        url: app.globalData.testUrl + '/Api/order/GetContract',
        method: 'POST',
        data: {
          order_id: vm.data.orderDetail.order_id
        },
        dataType: 'json',
        success: function (res) {
          console.log("获取电子合同", res)
          my.downloadFile({
            url: res.data.data.contract_url,
            success({ apFilePath }) {
              my.openDocument({
                filePath: apFilePath,
                fileType: 'pdf',
                success: (res) => {
                  console.log('open document success')
                }
              })
            }
          })
        },
        complete: function (res) {
          my.hideLoading(); //加载结束
        }
      });
    } else {
      my.showToast({
        type: 'none',
        content: '当前版本不支持此功能，请更新支付宝后查看',
        duration: 500,
        success: () => {

        },
      });
    }

  },
  // 查看账单
  toBill() {
    my.navigateTo({
      url: '../../mybill/mybill?order_id=' + this.data.orderDetail.order_id,
    });
  },

  onLoad(query) {
    const {
      link_source,
      zm_user_id,
      platform
     } = query

    // 如果是从外链跳转的
    if(my.getStorageSync({ key: 'isOtherApp'}).data=="isOtherApp"){
        app.getUserPhone((res2)=>{
        // app.globalData.user_id = res2.user_id
        //加载动画
        my.showLoading({
          content: '加载中...',
          delay: 0,
        });
        if (query.order_id) {
          var order_id = query.order_id; //订单号
        } else {
          var order_id = app.globalData.order_id;
        }

        this.setData({
          order_id: order_id,
          imgUrl: app.globalData.imgUrl
        })

        //获取订单详情
        this.getDetail("load"); 
        my.removeStorageSync({
          key: 'isOtherApp'
        });
       
        return
      })
    }

    // 检测是否从其它来源进来的
    app.setShareChannel(platform)
    
    //加载动画
    my.showLoading({
      content: '加载中...',
      delay: 0,
    });
    if (query.order_id) {
      var order_id = query.order_id; //订单号
    } else {
      var order_id = app.globalData.order_id;
    }

    this.setData({
      order_id: order_id,
      imgUrl: app.globalData.imgUrl
    })

    //获取订单详情
    // this.getDetail("load");

    if(link_source) {
      this.getUserLowerOrderState(zm_user_id, link_source)
    } else {
    this.getAlipayIdAndRefusalQuantity()

    }

  },
  onShow() {
    this.getDetail("load");
    if (this.data.order_id != "" && this.data.isloadorderDetail) {
      // this.getDetail("load");
    }
  },

  onShareAppMessage() {
    const { globalData: { title } } = getApp()
    const {
      order_id
    } = this.data
    return {
      title,
      desc: `${title} 信用免押 更多爆款超低价格`,
      path: `/page/mine/myorders/orderdetail/orderdetail?order_id=${order_id}&platform=miniProgram`,
    }
  },

  // 服务消息跳转，获取用户类型
  getUserLowerOrderState(zm_user_id, link_source) {
    let { testUrl } = app.globalData
    const { order_id } = this.data
    my.request({
      url: `${testUrl}/api/order/judgeJumpPage`,
      method: 'POST',
      data: {
        zm_user_id,
        order_id
      },
      success: (res) => {
        const {
          data,
          code,
          msg
        } = res.data
        if(code !== 1) {
          my.showToast({
            type: 'fail',
            content: msg,
            duration: 2000
          })
          return
        }
        let { 
          order_id,
          jump_page_type,
          user_voucher_id,
          exclusive_price,
          safe_id,
          attr_id,
          safe_info,
          is_default_select_safe_confirm_order: is_select_safe,
          is_first_month_one_yuan
        } = data


        if(jump_page_type === 2) {
          // 获取支付宝用户ID
          app.getAuth_base()
          
        }

      
        // 调取拒量接口，查看是否拒量用户（1是拒量用户）
        if(jump_page_type === 1) { 
            // 提交PV、UV接口
            my.request({
            url:  `${testUrl}/api/index/activityRecord`,
            data: {
              source: 4,
              user_id: zm_user_id
            },
            success: () => {
              my.request({
                url: `${testUrl}/api/help/getProjectConfig?key=user_tag_status`,
                method: 'get',
                success: (res) => {
                  const { data: { data } } = res
                  if(!data || data === '0') {
                    return
                  }
                  my.request({
                    url: `${testUrl}/api/index/getRefuseDiversionPageNum`,
                    method: 'get',
                    success: (res) => {
                      const jumpPage = {
                        0: '',
                        1: '/page/rent/h5/noSesameRentMachine/noSesameRentMachine',
                        2: '/page/rent/h5/noSesameRentMachine/refusalQuantity1/refusalQuantity1',
                        3: '/page/rent/h5/noSesameRentMachine/refusalQuantity2/refusalQuantity2',
                        4: '/page/rent/h5/noSesameRentMachine/refusalQuantity3/refusalQuantity3',
                        5: '/page/rent/h5/noSesameRentMachine/refusalQuantity4/refusalQuantity4',
                        6: '/page/rent/h5/noSesameRentMachine/refusalQuantity5/refusalQuantity5',
                        7: '/page/rent/h5/noSesameRentMachine/refusalQuantity6/refusalQuantity6',
                        8: '/page/rent/h5/noSesameRentMachine/refusalQuantity7/refusalQuantity7',
                      }
                      const { data: key, code, msg } = res.data
                      if(code !== 1) {
                        my.showToast({
                          type:'fail',
                          content: msg
                        })
                        return
                      }
                      if(jumpPage[key]) {
                        my.navigateTo({
                          url: jumpPage[key]
                        })
                      }
                    }
                  })
                }
              })
            }
          })
          return
        }

        is_first_month_one_yuan = is_first_month_one_yuan ? 1 : 0
        
        if(jump_page_type === 3) { // 跳转提交订单
          
          const params = `link_source=${link_source}&zm_user_id=${zm_user_id}&order_id=${order_id}`
          const s_m_user_voucher_id = `&s_m_user_voucher_id=${user_voucher_id}`
          const s_m_exclusive_price = `&s_m_exclusive_price=${exclusive_price}`
          const s_m_safe_id = `&s_m_safe_id=${safe_id}`
          const s_m_attr_id = `&s_m_attr_id=${attr_id}`
          const s_m_safe_info = `&s_m_safe_info=${JSON.stringify(safe_info)}`
          const s_m_is_select_safe = `&s_m_is_select_safe=${is_select_safe}`
          const s_m_is_first_month_one_yuan = `&s_m_is_first_month_one_yuan=${is_first_month_one_yuan}`

          const url = `/page/rent/confirm-order/confirm-order?${params}${s_m_user_voucher_id}${s_m_exclusive_price}${s_m_safe_id}${s_m_attr_id}${s_m_safe_info}${s_m_is_select_safe}${s_m_is_first_month_one_yuan}`

          my.redirectTo({
            url
          });
          
        }
        
      }
    })
  },

  // 获取用户状态是否是拒量用户随时刷新
  getAlipayIdAndRefusalQuantity() {
    let { testUrl, user_id } = app.globalData
    my.request({
      url:  `${testUrl}/api/user/getUserType`,
      method: 'POST',
      data: {
        zm_user_id: user_id
      },
      success: (res) => {
        let { user_type } = res.data.data
        
        if(user_type) {
          // 提交PV、UV接口
          my.request({
            url:  `${testUrl}/api/index/activityRecord`,
            data: {
              source: 4,
              user_id
            },
            success: () => {
              my.request({
                url: `${testUrl}/api/help/getProjectConfig?key=user_tag_status`,
                method: 'get',
                success: (res) => {
                  const { data: { data } } = res
                  if(!data || data === '0') {
                    return
                  }
                  my.request({
                    url: `${testUrl}/api/index/getRefuseDiversionPageNum`,
                    method: 'get',
                    success: (res) => {
                      const jumpPage = {
                        0: '',
                        1: '/page/rent/h5/noSesameRentMachine/noSesameRentMachine',
                        2: '/page/rent/h5/noSesameRentMachine/refusalQuantity1/refusalQuantity1',
                        3: '/page/rent/h5/noSesameRentMachine/refusalQuantity2/refusalQuantity2',
                        4: '/page/rent/h5/noSesameRentMachine/refusalQuantity3/refusalQuantity3',
                        5: '/page/rent/h5/noSesameRentMachine/refusalQuantity4/refusalQuantity4',
                        6: '/page/rent/h5/noSesameRentMachine/refusalQuantity5/refusalQuantity5',
                        7: '/page/rent/h5/noSesameRentMachine/refusalQuantity6/refusalQuantity6',
                        8: '/page/rent/h5/noSesameRentMachine/refusalQuantity7/refusalQuantity7',
                      }
                      const { data: key, code, msg } = res.data
                      if(code !== 1) {
                        my.showToast({
                          type:'fail',
                          content: msg
                        })
                        return
                      }
                      if(jumpPage[key]) {
                        my.navigateTo({
                          url: jumpPage[key]
                        })
                      }
                    }
                  })
                }
              })
            }
          })
        }
      }
    })
  },

  md(e){
    let order_id = e.currentTarget.dataset.orderId;
    my.redirectTo({
      url:"../../rent/confirm-order/confirm-order?orderid="+order_id
    });
  },
  //下拉刷新
  onPullDownRefresh() {
    this.getDetail("pulldown");
  },
  onReady() {
    this.animation = my.createAnimation({
      duration: 200,
    })
    const time = new Date();

    // 获取年、月、日
    const year = time.getFullYear();
    const month = time.getMonth() + 1; // 月份是从0开始计数的，所以要加1
    const day = time.getDate();
    this.setData({
      currentDate: `${year}/${month}/${day}`
    })
  },

  events: {
    onBack() {
      let pages = getCurrentPages(); // 当前页面
      let beforePage = pages[pages.length - 2]; // 上一页
      if(beforePage.orderList) {
        beforePage.orderList('click')
      }
    },
  },

  jumpNoSesameRentMachine() {
    my.navigateTo({
      url: '/page/rent/h5/noSesameRentMachine/noSesameRentMachine'
    })
  },

  moveMenu(e) {//点击更多按钮
    console.log(e);
    let vm = this;
    let _movegoodid = e.currentTarget.dataset.id;


    if (!vm.data.ismoveMenuBtn) {

      this.animation.rotate(0).step()
      this.setData({ animation: this.animation.export() })

    } else {
      this.animation.rotate(180).step()
      this.setData({ animation: this.animation.export() })
    }


    vm.setData({
      ismoveMenuBtn: !vm.data.ismoveMenuBtn
    })

  },
  onItemXuZu() {
    my.navigateTo({
      url: "../renewal/renewal?order_id=" + this.data.orderDetail.order_id
    })
  },
  onItemGuiHuan() {
    my.navigateTo({
      url: "../returngoods/returngoods?order_id=" + this.data.orderDetail.order_id + "&typeindex=3"
    })
  },
  onItemYiGuiHuan() {
    my.navigateTo({
      url: "../returngoods/returngoods?order_id=" + this.data.orderDetail.order_id + "&isGuiHuan=false"
    })
  },
  toGoodsDetail(e) {
    my.navigateTo({
      url: "../../../rent/goodsdetail/goodsdetail?id=" + e.currentTarget.dataset.goods_id
    })
  },
  goExpress() {
    my.navigateTo({
      url: "../express/express?order_id=" + this.data.orderDetail.order_id
    })
  },
  closekefu() {
    this.setData({
      kefuisShow: false
    })
  },
  showkefu() {
    this.setData({
      kefuisShow: true
    })
  },
  shangJiaPhone() {//商家客服
    my.makePhoneCall({
      number: this.data.orderDetail.mer_phone,
    });
  },
  pingTaiPhone() {//平台客服
    let app = getApp();
    my.makePhoneCall({
      number: app.globalData.pre_sale_phone,
    });
  },

  // 挽留弹窗继续下单取消
  confirmDeparture() {
    this.setData({
      isHidePlaceOrderPopup: false
    })
  },

  // 继续下单
  payment(e) {
  //   app.getUserInfo((res1) => {
  //     app.globalData.user_id = res1.user_id
  // })
  my.showLoading({
    content: '加载中...',
    delay: 0,
  });
  let {
    orderId: _order_id,
    is_face_auth
  } = e.currentTarget.dataset

  this.setData({
    isHidePlaceOrderPopup: false
  })
  if(!_order_id){
    return
  }
  is_face_auth = is_face_auth || this.data.orderDetail.is_face_auth

  const { testUrl, user_id: zm_user_id } = app.globalData
  my.request({
    url: `${testUrl}/Api/order/NopayFreeze`,
    method: 'POST',
    cache: false,
    data: {
      order_id: _order_id,
      zm_user_id
    },
    success: (res) => {
      const {
        status, data: {
          orderStr,
          order_id
        }
      } = res.data
      if (status == '1001') {

        let data = {
          order_id, //订单号
          status: "SUCCESS", //下单状态 
          zm_user_id
        }
        this.setData({
          orderStr
        })
        const { is_skip_face_auth } = this.data.orderDetail
        if(is_skip_face_auth) { // 刷单直接放过预授权
          my.request({
            url: `${testUrl}/api/user/userFaceAuthSuccess`,
            method: 'POST',
            data: {
              order_id
            },
            dataType: 'json',
            success: () => {
              this.preAuthorization(data)
            },
            fail: () => { // 成功和失败都拉起预授权
              this.preAuthorization(data)
            }
          })
          return
        }
      
      // 若已经人脸识别
        if(is_face_auth) {
          this.preAuthorization(data)
        } else {
          this.authentication(order_id, data)
      }

      } else if(res.data.status === '101') {
        my.confirm({
          title: res.data.msg,
          confirmButtonText: '咨询客服',
          cancelButtonText: '取消',
          success: (result) => {
            const { confirm } = result
            if(confirm) {
              this.setData({
                kefuisShow: true
              })
            }
          },
        });
      } else {
        my.showToast({
          type: 'fail',
          content: res.data.msg,
          duration: 2000,
        });
      }
    }, complete:  () => {
      my.hideLoading();
    }
  })
  },

  //预授权支付
  preAuthorization(data) {
    const { orderStr } = this.data
    my.tradePay({
      orderStr,
      success: (res) => {
        let { resultCode } = res
        if (resultCode == "9000") {//成功
          this.orderSuccess(data,  () => {//调用订单状态同步接口
              this.getDetail("load")
          })
        } else {
          this.getDetail("load");
          my.hideLoading();
        }
      },
      fail: () => {
        my.alert({
          title: '提示',
          content: '系统异常请联系客服处理',
          buttonText: '联系客服',
          success: () => {
            this.setData({
              kefuisShow: true,
            });
          }
        })
      },
      complete: () => {
        my.hideLoading(); //加载结束
      }
    })
  },
  // 人脸识别认证
  authentication(order_id, resetData) {
    let { testUrl, user_id: zm_user_id } = getApp().globalData;
    my.request({
      url: `${testUrl}/api/user/userFaceAuth`,
      method: 'POST',
      data: {
        zm_user_id,
        order_id,
      },
      dataType: 'json',
      success: (res) => {
        const { code, data: {
          certify_url: url, 
          certify_id: certifyId
        } } = res.data
        if (code === 1) {
          my.startAPVerify({
            url,
            certifyId,
            success: res => {
              if (res.resultStatus === "9000") {
                my.request({
                  url: `${testUrl}/api/user/userFaceAuthSuccess`,
                  method: 'POST',
                  data: {
                    order_id
                  },
                  dataType: 'json',
                  success: () => {
                    this.preAuthorization(resetData)
                  },
                  fail: () => { // 成功和失败都拉起预授权
                    this.preAuthorization(resetData)
                  }
                })
              } else {
                // my.showToast({
                //   content: res.resultStatus === "6001" ? "请先完成人脸识别" : '人脸识别失败！',
                // })
                this.setData({
                  isHidePlaceOrderPopup: true
                })
            }
          },
          fail: () => {
            my.alert({
              title: '提示',
              content: '系统异常请联系客服处理',
              buttonText: '联系客服',
              success: () => {
                this.setData({
                  kefuisShow: true,
                });
              }
            })
          }
        })
        }
      }, complete: () => {
        my.hideLoading(); //加载结束
      }
    })
  },

  withhold(_str, callback) {//商户代扣
    let vm = this;
    if(my.canIUse("paySignCenter")){
      my.paySignCenter({
        signStr: _str,
        success: (res) => {
          //console.log("代扣返回参数",res)
          if (res.resultStatus == "7000") {//协议签约成功
            let _agreement_no = JSON.parse(res.result).alipay_user_agreement_page_sign_response.agreement_no
            callback({
              agreement_no: _agreement_no
            })
          } else {
            my.hideLoading();
            vm.orderList('click');
            callback(false)
          }
        }
      });
    }else{
        my.hideLoading();
    }
  },


  orderSuccess(_data, callback) {//订单结果
    console.log('同步订单结果的_data:',_data)
    // my.showToast({
    //   content:'同步订单结果的_data:'+_data,
    //   duration: 1000,
    // })
   
    let vm = this;
    my.request({
      url: app.globalData.testUrl + '/Api/order/OrderSuccess',
      method: 'POST',
      data: _data,
      dataType: 'json',
      success: function (res) {
        if (res.data.status == "1001") {
          my.showToast({
            type: 'none',
            content: '支付成功~',
            duration: 1000,
            success: () => {
              callback(true)
              // vm.orderList('click');
            }
          });
        } else {
          my.hideLoading();
          my.showToast({
            type: 'none',
            content: '系统繁忙请重试~',
            duration: 1000,
            success: () => {
            }
          });
        }
      },
      complete: function (res) {
        // console.log(res);
        my.hideLoading();

      }
    })
  }
});
